<template>
  <div>
    <div class="flex-justify-end">
      <el-button type="primary" size="mini" class="mar-btm-20" @click="clickCreateBtn">新增组件</el-button>
      <el-button type="danger" size="mini" class="mar-btm-20" v-if="!isProtocol" @click="clickSyncBtn">同步组件</el-button>
    </div>
    <EZTable v-loading="tableLoading"
             :table-id="tableId"
             :table-hdl="tableHdl"
             :rows="componentList"
             @pageChanged="getComponentList"
             @sizeChanged="getComponentList"
             @filterChange="getComponentList"
             :fit-table="false">
      <EmptyContent slot="empty" :opt-data="componentOptData"></EmptyContent>
    </EZTable>
    <el-dialog :visible.sync="showComponentDialog" :append-to-body="true" :close-on-click-modal="false" :title="isEditComponent ? '修改小组件' : '新增小组件'" width="750px" top="100px">
      <widgetAdd @closeDialog="showComponentDialog=false" @submitDialog="submitDialog"
                 :componentForm="componentForm" :isEditComponent="isEditComponent" :isProtocol="isProtocol"></widgetAdd>
    </el-dialog>

  </div>
</template>
<script>
  import EZTable from "@/components/table/EZTable.vue";
  import {tableIdConfig, tableOptBtnConfig} from "@/config/table";
  import componentTableCfg from "@/config/table/protocolComponent";
  import widgetAdd from "@/components/IDE/WidgetAdd.vue"
  import {assembleTableOptBtn, getTableConfig, TableStateHdl} from "@/modules/routeParamStateHdl";
  import {
    confirmHandle,
    deepCopyWithJson, downloadFileApi,
    editorConfigPreview, getUserInfo,
    JSONParse, messageHandle,
  } from "@/utils";
  import {routerMeta} from "@/router/routerMeta";
  import {
    componentCategoryArray,
    componentTypeArray,
    uploadPreviewType,
    userRoleCfg
  } from "@/config/common";
  import {msgCode} from "@/config/string";

  export default {
    name: "GeneralProtocolWidget",
    components: {EZTable, widgetAdd},
    props: {
      protocolId:{ type: String, default: ''},
      isProtocol:{ type: Boolean, default: false},//是否是通用协议
      deviceProtocolId:{ type: String, default: ''},
      genDeviceType:{ type: String, default: ''},
      currentGeneralProtocolId:{ type: String, default: ''},
    },
    data() {
      return {
        userRoleCfg: userRoleCfg,
        userInfo: getUserInfo(),
        previewType: uploadPreviewType,
        tableId: tableIdConfig.protocolComponent,
        tableLoading: true,
        tableHdl: null,
        componentList: [],
        isEditComponent: false,
        showComponentDialog: false,
        componentForm: {},
        componentTypeArray: componentTypeArray,
        componentCategoryArray: componentCategoryArray,
        detailConfig: {},
      }
    },
    mounted() {
      this.initTableConfig();
      this.initComponentForm();
      this.getComponentList();
    },
    watch: {
      isProtocol() {
        this.getComponentList();
      },
    },
    computed: {
      componentOptData() {
        return [
          {
            type: 'btn',
            label: '新增组件',
            icon: 'icon-tianjia',
            callback: () => {
              this.clickCreateBtn();
            }
          }
        ];
      },
    },
    methods: {
      initComponentForm() {
        this.componentForm = {
          type: 'compositeWidget',
          category: 'deviceWidget',
          name: "",
          version: "",
          devices: [],
          previewImages: [],
          theme: 'theme1',
          remarks: '',
          group: '',
          widgetSize: {
            rows: 1, columns: 1
          },
          deviceType:'',
          protocolId: '',
          isWidget: true,
          widgetType: '',
          generalProtocolId: '',

        };
      },

      initTableConfig() {
        if (this.tableHdl) return;
        const {columns = [], filters = []} = getTableConfig(this.tableId, componentTableCfg);
        assembleTableOptBtn(columns, ({type = '', data = {}}) => {
          if (!type) return;
          const component = deepCopyWithJson(data);
          switch (type) {
            case tableOptBtnConfig.edit.type:
              this.showComponentDialog = true;
              this.isEditComponent = true;
              this.commonSetVal(component)
              break;
            case tableOptBtnConfig.select.type:
              window.open(this.$router.resolve({
                name: routerMeta.componentEditor.name,
                params: {cid: component._id}
              }).href, '_blank');
              break;
            case tableOptBtnConfig.copy.type:
              this.copyComponent(component);
              break;
            case tableOptBtnConfig.preview.type: {
              //预览
              editorConfigPreview({type: 'component', componentId: component._id});
              break;
            }
            case tableOptBtnConfig.delete.type:
              this.deleteComponent(component);
              break;
            case tableOptBtnConfig.audit.type:
              this.addAuditComponent(component)
              break;
            case tableOptBtnConfig.deleteAudit.type:
              this.deleteAuditComponent(component)
              break;
            case tableOptBtnConfig.export.type:
              this.exportComponentConfig(component);
              break;
            case tableOptBtnConfig.group.type:
              this.groupForm.group = component.group;
              this.setGroup(component);
              break;
            case tableOptBtnConfig.release.type:
              this.setRelease(component);
              break;
            case tableOptBtnConfig.deleteRelease.type:
              this.setDeleteRelease(component);
              break;
            case tableOptBtnConfig.exportZip.type:
              this.exportComponentZipConfig(component);
              break;
            default:
              break;
          }
        });
        this.tableHdl = new TableStateHdl(this.$route.name, this.tableId, columns, filters);
      },

      getComponentList() {
        const selector={}
        if(this.isProtocol){
          selector.generalProtocolId=this.protocolId;
        }else {
          selector.protocolId=this.deviceProtocolId;
        }
        this.tableLoading = true;
        const tableParam = this.tableHdl.assembleTableParam();
        API.component.componentList({...tableParam, selector}).then(result => {
          this.tableLoading = false;
          const {data = [], total = 0} = result;
          this.componentList = data.map(d => {
            return {
              ...d,
              status: d.status === 0 ? '未发布' : d.status === 1 ? '审核中' : d.status === 2 ? '已发布' : d.status === 2 ? '已下架' : '--',
              widgetSizes: `${d.widgetSize.rows} x ${d.widgetSize.columns}`,
              releaseBtn: d.status === 0,
              deleteReleaseBtn: d.status === 2,
            }
          });
          this.tableHdl.total = total;
        }).catch(err => {
          console.log('err', err)
          this.tableLoading = false;
        });
      },
      clickCreateBtn() {
        this.isEditComponent = false;
        this.initComponentForm()
        this.componentForm.deviceType=this.genDeviceType
        if(this.isProtocol){
          this.componentForm.generalProtocolId=this.protocolId
        }else{
          this.componentForm.widgetType='device'
          this.componentForm.protocolId=this.deviceProtocolId
        }
        this.showComponentDialog = true;
      },
      clickSyncBtn() {
        confirmHandle({label: `确定要同步小组件吗?`}).then(() => {
          this.tableLoading = true
          const params = {
            protocolId: this.deviceProtocolId,
            generalProtocolId: this.currentGeneralProtocolId
          }
          API.generalProtocol.generalProtocolRelated(params).then(result => {
            messageHandle({code: msgCode.COPY_SUCCESS, title: '设备协议关联通用协议小组件'});
            this.getComponentList();
            this.tableLoading = false
          }).catch(err => {
            this.tableLoading = false
            console.log('err', err)
          });
        }).catch(() => {
        });

      },
      // 复制
      copyComponent(row) {
        this.$confirm(`确定要复制【${row.name}】的组件吗?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.tableLoading = true;
          API.component.componentClone({_id: row._id}).then((resp) => {
            this.$message({
              message: "组件复制成功!",
              type: "success",
              duration: 1500,
            });
            this.tableLoading = false;
            this.getComponentList();
          }).catch((err) => {
            console.log("err: ", err);
            this.tableLoading = false;
          });
        }).catch(() => {
        });
      },
      //删除
      deleteComponent(row) {
        this.$confirm(`确定要删除【${row.name}】的组件吗?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.tableLoading = true;
          API.component.componentDelete({componentId: row._id}).then((resp) => {
            this.$message({
              message: "组件删除成功!",
              type: "success",
              duration: 1500,
            });
            this.tableLoading = false;

            this.getComponentList();
          }).catch((err) => {
            console.log("err: ", err);
            this.tableLoading = false;
          });
        }).catch(() => {
        });
      },
      //发布
      setRelease(row) {
        this.commonSetVal(row)
        this.componentForm.status = 2;
        API.component.componentEdit(this.componentForm).then((resp) => {
          this.componentFormLoading = false;
          this.$message({
            message: "组件发布成功!",
            type: "success",
            duration: 1500,
          });
            this.getComponentList();
        }).catch((err) => {
          console.log("err: ", err);
        });
      },
      //取消发布
      setDeleteRelease(row) {
        this.commonSetVal(row)
        this.componentForm.status = 0;
        API.component.componentEdit(this.componentForm).then((resp) => {
          this.$message({
            message: "组件取消发布!",
            type: "success",
            duration: 1500,
          });
          this.getComponentList();
        }).catch((err) => {
          console.log("err: ", err);
        });
      },
      commonSetVal(row) {
        const {
          _id,
          type,
          category,
          name,
          version,
          theme = 'theme1',
          devices = [],
          previewImages = [],
          remarks,
          group = '',
          deviceType,
          widgetSize = {rows: 1, columns: 1},
          protocolId,
          isWidget,
          widgetType,
          generalProtocolId
        } = row;
        this.componentForm = {
          _id, type, category, name, version, theme,
          devices, previewImages, remarks, group, deviceType, widgetSize, protocolId, isWidget, widgetType,generalProtocolId
        };
      },
      submitDialog() {
        this.showComponentDialog = false
        this.getComponentList()
      }
    },

  }
</script>
<style scoped lang="less">

</style>
